﻿#include "binaryrainwidget.h"
#include <QPainter>
#include <QRandomGenerator>
#include <QString>
#include <QtMath>

BinaryRainWidget::BinaryRainWidget(QWidget *parent)
    : QWidget(parent), timer(new QTimer(this))
{
    setAttribute(Qt::WA_TranslucentBackground);
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint);

    connect(timer, &QTimer::timeout, this, &BinaryRainWidget::updateRain);
    timer->start(5); // 30 ms interval for smoother animation

    // Initialize rain drops
    for (int i = 0; i < width() / 10; ++i) {
        RainDrop drop;
        drop.x = QRandomGenerator::global()->bounded(width());
        drop.y = QRandomGenerator::global()->bounded(-height(), height());
        drop.length = QRandomGenerator::global()->bounded(10, 20);
        drop.color = QColor(0, 255, 0, qrand() % 256 + 50);
        drop.text = QString(QRandomGenerator::global()->bounded(4, 8), QChar('0' + QRandomGenerator::global()->bounded(2)));
        rainDrops.append(drop);
    }
}

BinaryRainWidget::~BinaryRainWidget()
{
    delete timer;
}

void BinaryRainWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.fillRect(rect(), Qt::black);

    for (auto &drop : rainDrops) {
        painter.setPen(drop.color);
        painter.drawText(drop.x, drop.y, drop.text);
    }
}

void BinaryRainWidget::resizeEvent(QResizeEvent *)
{
    // Reinitialize rain drops on resize
    rainDrops.clear();
    for (int i = 0; i < width() / 10; ++i) {
        RainDrop drop;
        drop.x = QRandomGenerator::global()->bounded(width());
        drop.y = QRandomGenerator::global()->bounded(-height(), height());
        drop.length = QRandomGenerator::global()->bounded(10, 20);
        drop.color = QColor(0, 255, 0, QRandomGenerator::global()->bounded(256));
        drop.text = QString(QRandomGenerator::global()->bounded(4, 8), QChar('0' + QRandomGenerator::global()->bounded(2)));
        rainDrops.append(drop);
    }
}

void BinaryRainWidget::updateRain()
{
    for (auto &drop : rainDrops) {
        if (drop.y >= height()) {
            drop.y = -qrand() % drop.length;
        } else {
            drop.y += 1;
        }
    }

    update(); // Trigger repaint
}
